﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NBusiness.Query;
using System.Data;

namespace NBusiness.Data.Providers.SqlServer.Query
{
    public class SqlQuery : IQuery
    {
        #region IQuery Members
        private List<IStatement> _statements = new List<IStatement>();
        
        public IList<IStatement> Statements
        {
            get { return _statements; }
        }

        public ISelect Select()
        {
            ISelect select = new SqlSelect();
            _statements.Add(select);
            return select;
        }

        public IInsert Insert()
        {
            IInsert insert = new SqlInsert();
            _statements.Add(insert);
            return insert;
        }

        public IUpdate Update()
        {
            IUpdate update = new SqlUpdate();
            _statements.Add(update);
            return update;
        }

        public IDelete Delete()
        {
            IDelete delete = new SqlDelete();
            _statements.Add(delete);
            return delete;
        }

        public IStatement Go()
        {
            IStatement go = new SqlGo();
            _statements.Add(go);
            return go;
        }

        public event Action<ILoader> Load;

        public void OnLoad(ILoader loader)
        {
            if (Load != null)
                Load(loader);
        }

        #endregion

        #region IRelationalElement Members

        public string ToSql()
        {
            return ToSql(new SqlQueryContext());
        }

        public string ToSql(IQueryContext context)
        {
            StringBuilder builder = new StringBuilder();
            for(int x=0;x<Statements.Count;x++)
            {
                if (x > 0) 
                    builder.AppendLine();

                IStatement statement = Statements[x];
                builder.Append(statement.ToSql());
            }

            return builder.ToString();
        }

        #endregion
    }
}
